package com.dao;

import com.dao.UserDAO;
import com.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.dao.EmptyResultDataAccessException;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDAOImpl implements UserDAO {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 定义 SQL 语句
    private static final String SQL_FIND_ALL = "SELECT * FROM users";
    private static final String SQL_FIND_BY_ID = "SELECT * FROM users WHERE id = ?";
    private static final String SQL_INSERT = "INSERT INTO users (user_name, user_password, user_role, state) VALUES (?, ?, ?, ?)";
    private static final String SQL_UPDATE = "UPDATE users SET user_name = ?, user_password = ?, user_role = ?, state = ? WHERE id = ?";
    private static final String SQL_DELETE = "DELETE FROM users WHERE id = ?";

 
    private static final RowMapper<User> ROW_MAPPER = (ResultSet rs, int rowNum) -> {
        User user = new User();
        user.setId(rs.getInt("id"));
        user.setUserName(rs.getString("user_name"));
        user.setUserPassword(rs.getString("user_password"));
        user.setUserRole(rs.getString("user_role"));
        user.setState(rs.getString("state"));
        return user;
    };

    // CRUD 方法
    /* 查找全部数据 */
    @Override
    public List<User> findAll() {
        return jdbcTemplate.query(SQL_FIND_ALL, ROW_MAPPER);
    }
  /* 根据ID查找数据 */
    @Override
    public User findById(Integer id) {
        try {
            return jdbcTemplate.queryForObject(SQL_FIND_BY_ID, new Object[]{id}, ROW_MAPPER);
        } catch (EmptyResultDataAccessException e) {
            return null; // 或者抛出自定义异常
        }
    }
/* 新增数据 */
    @Override
    public void save(User user) {
        jdbcTemplate.update(SQL_INSERT,
                user.getUserName(),
                user.getUserPassword(),
                user.getUserRole(),
                user.getState());
    }
/* 更新数据 */
    @Override
    public void update(User user) {
        jdbcTemplate.update(SQL_UPDATE,
                user.getUserName(),
                user.getUserPassword(),
                user.getUserRole(),
                user.getState(),
                user.getId());
    }
/* 根据id删除数据 */
    @Override
    public void deleteById(Integer id) {
        jdbcTemplate.update(SQL_DELETE, id);
    }
}